package com.fg.cloud.system.controller.order;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.construction.Select;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.manager.entry.order.OrderDetailEntity;
import com.fg.cloud.manager.entry.order.OrderInfoEntity;
import com.fg.cloud.manager.service.system.InvoiceManageService;
import com.fg.cloud.manager.service.system.SystemOrderService;

@Controller
@RequestMapping("SystemOrder")
public class SystemOrderController {

	@Autowired
	private SystemOrderService systemOrderService;
	@Autowired
	private InvoiceManageService invoiceManageService;
	/**
	 * 跳转到订单首页
	 * */
	@RequestMapping("index")
	private String Index(){
		return "order/orderinfo";
	}
	
	/**
	 * 跳转到订单首页
	 * */
	@RequestMapping("detail")
	private String Detail(){
		return "order/NewFile";
	}
	
	/**
	 * 查询全部订单
	 * condition: 
	 * */
	@RequestMapping(value="/findBySenior",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Map<String ,Object> findBySenior(HttpServletRequest req , HttpServletResponse resp,
			String keyword,Long facId,
			Integer page, Integer rows, String sort, String order){
		try{
			PageUtils<OrderInfoEntity> pageinfo = new PageUtils<OrderInfoEntity>(page, rows, sort, order);
			Map<String,Object> conditions = new HashMap<>();
			conditions.put("keyword", keyword);
			pageinfo.setCondition(conditions);
			pageinfo.setFacId(facId);
			systemOrderService.findBySenior(pageinfo);
			Map<String ,Object> usmap = new HashMap<String ,Object>();
			usmap.put("total", pageinfo.getTotal());
			usmap.put("rows", pageinfo.getData());
			return usmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 删除订单
	 * */
	@RequestMapping(value="/deleteOrder",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Long deleteProdect(HttpServletRequest req , HttpServletResponse resp ,String ids){
		List<Long> id = toLong(ids);
		Long flag = systemOrderService.delete(id);
		return flag;
	}
	
	public List<Long> toLong(String ids){
		String[] id1 = ids.split(",");
		List<Long> id = new ArrayList<Long>();
		for(int i = 0;i<id1.length;i++){
			if(!"".equals(id1[i]) && id1[i]!= null){
				id.add(Long.valueOf(id1[i]));
			}
		}
		
		return id;
	}
	
	/**
	 * 查询订单详情
	 * */
	@RequestMapping(value="/orderDetail",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public OrderInfoEntity orderDetail(HttpServletRequest req , HttpServletResponse resp,Long id,Long facId){
		try{
			if(id == null || id <= 0 || facId == null || facId <= 0){
				return null;
			}
			//Map<String ,Object> usmap = new HashMap<String ,Object>();
			OrderInfoEntity os = systemOrderService.findOrderDetail(id,facId);
			//List<OrderDetailEntity> detail = systemOrderService.findOrderDetail(id,facId);
			//usmap.put("rows", detail);
			return os;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 查询订单详情
	 * */
	@RequestMapping(value="/orderDetailList",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Map<String ,Object> orderDetailList(HttpServletRequest req , HttpServletResponse resp,Long id,Long facId){
		try{
			if(id == null || id <= 0 || facId == null || facId <= 0){
				return null;
			}
			Map<String ,Object> usmap = new HashMap<String ,Object>();
			//OrderInfoEntity os = systemOrderService.findOrderDetail(id,facId);
			List<OrderDetailEntity> detail = systemOrderService.orderDetailList(id,facId);
			usmap.put("rows", detail);
			return usmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 查询发票,厂商select模式
	 * */
	@RequestMapping(value="/selectForFactory",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public List<Select> selectForFactory(HttpServletRequest req , HttpServletResponse resp, Long facId){
		try {
			/*if(facId == null || facId <= 0){
				return null;
			}*/
			Map<String, Object> usmap = new HashMap<String, Object>();
			usmap.put("facId", facId);
			List<Select> list = invoiceManageService.selectAllInvoice(usmap);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Description:订单修改
	 * @param req
	 * @param resp
	 * @param order  订单信息
	 * @author liushengchao
	 * @date  2017年8月31日下午3:44:53
	 */
	@RequestMapping(value="/modify",method={RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Result modifyOrder(HttpServletRequest req,HttpServletResponse resp, OrderInfoEntity entity) {
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
			entity.setDeliveryDate(sdf.parse(entity.getDeliveryDateStr()));
			Result result =  systemOrderService.modifyOrder(entity);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * Description:订单详情修改
	 * @param req
	 * @param resp
	 * @param order  订单信息
	 * @author liushengchao
	 * @date  2017年8月31日下午3:44:53
	 */
	@RequestMapping(value="/modifyDetail",method={RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Result modifyDetail(HttpServletRequest req,HttpServletResponse resp, String date, String amount) {
		try {
			OrderDetailEntity detail = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(date), OrderDetailEntity.class);
			if(amount != null && !"".equals(amount)){
				detail.setAmount(BigDecimal.valueOf(Long.valueOf(amount)));
			}else{
				detail.setAmount(BigDecimal.valueOf(0));
			}
			Result result =  systemOrderService.modifyOrderDetail(detail);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * Description:订单详情删除
	 * @param req
	 * @param resp
	 * @param order  订单信息
	 * @author liushengchao
	 * @date  2017年8月31日下午3:44:53
	 */
	@RequestMapping(value="/deleteDetail",method={RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public Result deleteDetail(HttpServletRequest req,HttpServletResponse resp, Long id) {
		try {
			if(id != null && id<=0){
				return Result.result(null, false, StatusCode.SAVEERROR, "id不能为空");
			}
			Result result =  systemOrderService.deleteDetail(id);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	

	   String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCWGbT70LL0VTXOXMUstnv1r7Axx0NDXY5n/DH3bq3X2qPibTtm6s7jWpNv9Xq1GrBI2MI+VM1TK+GTItrsBf8M5SK4CXg1zuGaq7wum8TYwrJ622zX1dJv01LbGYpkx9PvM2+l9eiYhpOhHbvjSItJIP9uG119/LmbF5n5lqnku1QCb36aawNaL24KEJ2Fr61HRz3uvPrOCTglNlBhxYBhNbolOmN0/MLOeBWUButqN4Plu+Hxrtb438lZOEJAcVWuwI40gleL9fiSs/gVIw7tzg02EKUVjY+3XNwaWBJ7VJY6qfCjBGFw0wQnOEn8HG0g8ut9xEnMNfoXBHCfmLQJAgMBAAECggEAU9Bo+g/QTZTjJacxxsTjNQ50cWdWDODJ6xCtCgA4fIau6nmaKN7GxbdHCsZlTYlolFTNKicKO/4NyK421oKGp7mvCFrpUAqEeWyZ+OCsK2mUZfvurBrOlfjHlGaPm7Tlh/UNy/sjdT/4YYgL6V8Rv7T4TJBlRTuAnLSyGudhWMHSBUrxbBMamx658UCPm3/qjZG5tWT98i5C1vQ27k2Ui2Cv+agLuZhBaS0AvCmw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McdDQ12OZ/wx926t19qj4m07ZurO41qTb/V6tRqwSNjCPlTNUyvhkyLa7AX/DOUiuAl4Nc7hmqu8LpvE2MKyetts19XSb9NS2xmKZMfT7zNvpfXomIaToR2740iLSSD/bhtdffy5mxeZ+Zap5LtUAm9+mmsDWi9uChCdha+tR0c97rz6zgk4JTZQYcWAYTW6JTpjdPzCzngVlAbrajeD5bvh8a7W+N/JWThCQHFVrsCONIJXi/X4krP4FSMO7c4NNhClFY2Pt1zcGlgSe1SWOqnwowRhcNMEJzhJ/BxtIPLrfcRJzDX6FwRwn5i0CQIDAQAB";
	   String app_id = "2017110809804050";
	/**
	 * 支付宝订单付款
	 * 
	 * */
	@RequestMapping(value="/payTest",method={RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	public void test(HttpServletRequest httpRequest,
	            HttpServletResponse httpResponse) throws ServletException, IOException {
		   
		   AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",app_id,
	    			merchant_private_key,"json","GBK",alipay_public_key,"RSA2");
			AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
			alipayRequest.setReturnUrl("http://yfx1688.com/");
			alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
			alipayRequest.setBizContent("{" +
			"    \"out_trade_no\":\"2015032001010100143351\"," +
			"    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
			"    \"total_amount\":0.01," +
			"    \"subject\":\"Iphone6 16G\"," +
			"    \"body\":\"Iphone6 16G\"," +
			"    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
			"    \"extend_params\":{" +
			"    \"sys_service_provider_id\":\"2088511833207846\"" +
			"    }"+
			"  }");//填充业务参数
			String form="";
			try {
			form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
			} catch (AlipayApiException e) {
			e.printStackTrace();
			}
			
			//form = sanitizing(form);
			//System.out.println(form);
			httpResponse.setContentType("text/html;charset=UTF-8");
			httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
			httpResponse.getWriter().flush();
			httpResponse.getWriter().close();
		}
	
	/**
	 * 转账到支付宝
	 * */
	@RequestMapping(value="/payToZhi",method={RequestMethod.GET,RequestMethod.POST} )
	@ResponseBody
	private void payToZhi() throws AlipayApiException{
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",app_id,
			merchant_private_key,"json","GBK",alipay_public_key,"RSA2");
		AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
		request.setBizContent("{" +
		"\"out_biz_no\":\"2015032001010100143351\"," +
		"\"payee_type\":\"ALIPAY_LOGONID\"," +
		"\"payee_account\":\"13864011752\"," +
		"\"amount\":\"0.1\"," +
		"\"payer_show_name\":\"单据付款\"," +
		"\"payee_real_name\":\"陈银龙\"," +
		"\"remark\":\"转账备注\"" +
		"  }");
		AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
		if(response.isSuccess()){
		System.out.println("调用成功");
		} else {
		System.out.println("调用失败");
		}
	}
}
